package com.jiahe.blog.common.handler;

import com.alibaba.fastjson.JSON;
import com.jiahe.blog.dao.UserAuthDao;
import com.jiahe.blog.entity.UserAuthEntity;
import com.jiahe.blog.model.dto.UserInfoDTO;
import com.jiahe.blog.model.response.BlogResponse;
import com.jiahe.blog.utils.ServletUtils;
import com.jiahe.blog.utils.StringUtils;
import com.jiahe.blog.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Autowired
    private UserAuthDao userAuthDao;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserInfoDTO loginUser = UserUtils.getLoginUser();
        // 更新用户ip，最近登录时间
        updateUserInfo(loginUser);
        String msg = StringUtils.format("用户：{} 登录成功 ", loginUser.getNickname());
        ServletUtils.renderString(response, JSON.toJSONString(BlogResponse.success(msg,loginUser)));
    }

    /**
     * 更新用户信息
     */
    public void updateUserInfo(UserInfoDTO loginUser) {
        UserAuthEntity userAuth = UserAuthEntity.builder()
                .id(loginUser.getId())
                .ipAddr(loginUser.getIpAddr())
                .ipSource(loginUser.getIpSource())
                .lastLoginTime(loginUser.getLastLoginTime())
                .build();
        userAuthDao.updateById(userAuth);
    }
}
